package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 关于 User表涉及的操作
// 1.根据用户名查询用户信息(实现登录的时候)
// 2.根据用户的id查询用户信息(获取文章的时候，根据博客的userId拿到作者的信息)
public class UserDao {

    // 1.根据用户名查询用户信息(实现登录的时候)
    public User select(String username) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1.连接数据库
            connection = DBUtil.getConnection();
            // 2.构造SQL语句
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1, username);
            // 3.执行SQL
            resultSet = statement.executeQuery();
            // 4.遍历结果集
            if (resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }

    // 2.根据用户的id查询用户信息(获取文章的时候，根据博客的userId拿到作者的信息)
    public User select(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            // 1.连接数据库
            connection = DBUtil.getConnection();
            // 2.构造SQL语句
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1, userId);
            // 3.执行SQL
            resultSet = statement.executeQuery();
            // 4.遍历结果集
            if (resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return null;
    }


}
